package com.konka.spring.framework.beans.support;

import com.konka.spring.framework.annotation.Controller;
import com.konka.spring.framework.annotation.Service;
import com.konka.spring.framework.beans.config.BeanDefinition;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

/**
 * @author konka
 * @date 2023/2/8
 * @description:
 */
public class BeanDefinitionReader {

    /**
     * 存储配置扫描包路径下所有的类，包括未加controller等注解的类
     */
    private Set<String> initScanClazzSet = new HashSet<String>();
    /**
     * 配置
     */
    private Properties properties = new Properties();

    public BeanDefinitionReader(String... locations) {
        //1、加载Properties文件
        doLoadConfig(locations[0]);

        //2、扫描相关的类
        doScanner(properties.getProperty("scanPackage"));
    }

    /**
     * 将类转化为BeanDefinition
     * @return
     */
    public List<BeanDefinition> loadBeanDefinition(){
        List<BeanDefinition> result = new ArrayList<>();

        //解析扫描类集合，填充beanMap和mapping
        try {
            for (String clazzName : initScanClazzSet) {
                Class<?> clazz = Class.forName(clazzName);
                //接口不做处理
                if (clazz.isInterface()){ continue; }

                Object instance = clazz.newInstance();
                //beanName 为类名首字母小写
                String beanName = toLowerFirstCase(clazz.getSimpleName());
                if (clazz.isAnnotationPresent(Controller.class)){
                    result.add(new BeanDefinition(beanName,clazz.getName()));
                }else if (clazz.isAnnotationPresent(Service.class)){
                    Service service = clazz.getAnnotation(Service.class);
                    String aliasBeanName = service.value();
                    if (aliasBeanName!=null && !"".equals(aliasBeanName)){
                        beanName = aliasBeanName;
                    }
                    result.add(new BeanDefinition(beanName,clazz.getName()));
                    //service 实现类
                    //service接口，key为接口类名
                    for (Class<?> anInterface : clazz.getInterfaces()) {
                        result.add(new BeanDefinition(anInterface.getName(),clazz.getName()));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 加载配置文件
     * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {
        //读取web.xml servlet的init-param 获得application.properties文件输入流
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation.replaceAll("classpath:",""));
        //加载application.properties文件
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 扫描相关类
     * @param scanPackage
     */
    private void doScanner(String scanPackage){
        //com.konka.demo 将 "." 替换为 "/" -> /com/konka/demo
        //获得扫描包路径
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File scanFileDir = new File(url.getFile());
        for (File file : scanFileDir.listFiles()) {
            if (file.isDirectory()){
                doScanner(scanPackage + "." +file.getName());
            }else {
                //如果不是java类，跳过不扫描
                if (!file.getName().endsWith(".class")){continue;}
                String clazzName = scanPackage + "." + file.getName().replace(".class", "");
                //将包路径下全部的类都放在set中
                initScanClazzSet.add(clazzName);
            }
        }
    }

    /**
     * 首字符变小写
     * @param simpleName
     * @return
     */
    private String toLowerFirstCase(String simpleName){
        char[] charArray = simpleName.toCharArray();
        charArray[0] += 32;
        return String.valueOf(charArray);
    }

    /**
     * 将配置信息提供出来
     * @return
     */
    public Properties getConfig() {
        return this.properties;
    }
}
